package xyz.thoughtset.viewer.common.api.advice;

import xyz.thoughtset.viewer.common.api.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class SuccessResponseAdvice {
    @Autowired
    private ObjectMapper mapper;

    @Around("execution(* xyz.thoughtset.viewer.common.api.controller.BaseController+.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object body;
        try{
            body = pjp.proceed();
        }
        catch (Exception e) {throw e;}
        if (body instanceof Result) {
            return body;
        }
        if (body instanceof ResponseEntity) {
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) body;
            return ResponseEntity.status(responseEntity.getStatusCode())
                    .headers(responseEntity.getHeaders())
                    .body(responseEntity.getBody());
        }
        byte[] bytes= mapper.writeValueAsBytes(body);
        if (body instanceof String) {
            return mapper.writeValueAsString(Result.success(body,bytes));
        }

        return Result.success(body,bytes);
    }
}
